<?php

/**
* @copyright   (C) 2010 iJoomla, Inc. - All rights reserved.
* @license  GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html) 
* @author  iJoomla.com webmaster@ijoomla.com
* @url   http://www.ijoomla.com/licensing/
* the PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript  
* are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0 
* More info at http://www.ijoomla.com/licensing/
*/

defined('_JEXEC') or die('Restricted access');
	
class QuestionMultiplePerRowMenus{
	
	function QuestionMultiplePerRowMenus(){
	}
	
	function display($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){		
		$return_content_array = array();		
		$return = "";
		$answer = "";
		$question_class = isset($params->question)? $params->question : "";
		$question_description = isset($params->question_description)? $params->question_description : "";		
		$javascript = "";
		$entered = "";
		$row_class = $params->table_row2;
		$row_class_ok = "true";
		$columns = $this->getColumns($question_id);
		$answers = $this->getAnswers($question_id);
		$validation = "";
		
		$return .= '<table width="100%" class="table_question">';
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .=           $question_details["0"]["title"];
		if($question_details["0"]["required"] == "1"){
			$return .= '<span class="question_required"> *</span>';
			$javascript = ' onchange="setentertext(form.q'.$question_id.', this)" ';
			$validation = $this->createValidation($answers, $question_id, $question_details["0"]["title"]);						
		}
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		if($question_details["0"]["description"] != ""){
			$return .='<tr>';
			$return .= 	 '<td class="'.$question_description.'">';
			$return .=       $question_details["0"]["description"];
			$return .= 	 '</td>';
			$return .='</tr>';
		}
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		
		$return .= 			'<table width="100%">';		
		$return .= 	  			'<tr class="'.$params->column_heading.'">';
		$return .= 	     			'<td width="40%">';
		$return .= 	         			'<input type="hidden" value="checkbox" name="question['.$question_id.'][type]">';
    	$return .= 	         			'<input type="hidden" value="matrix" name="question['.$question_id.'][orientation]">';
		$return .= 	     			'</td>';
		//create table header
		if(isset($columns) && count($columns)>0){
			foreach($columns as $key=>$value){
				$return .= 	 		'<td align="center" class="'.$params->column_heading.'">'.$value["value"].'</td>';
			}
		}		
		$return .= 	  			'</tr>';
		//create table content
		if(isset($answers) && count($answers)>0 && isset($columns) && count($columns)>0){
			$all_values = array();
			if(isset($completed["view_response"]) && $completed["view_response"]=="true"){
				$database_values = $this->getValue($question_id, $session_id);
				if(count($database_values) > 0){
					foreach($database_values as $key=>$data_value){
						$all_values[$data_value["m_id"]."_".$data_value["a_id"]] = $data_value["ac_id"];
					}
				}
			}
			foreach($answers as $key=>$value){				
				$count = 1;
				if($row_class_ok == "true"){
					$row_class = $params->table_row2;
					$row_class_ok = "false";
				}
				else{
					$row_class = $params->table_row1;
					$row_class_ok = "true";
				}
				$return .= 	    '<tr class="'.$row_class.'">';
				$return .= 	    	'<td align="right"><span class="'.$params->row_heading.'">'.trim($value["value"]).'</span></td>';					
					foreach($columns as $key_col=>$val_col){						
						$selected_values = $this->getSelectedValues($question_id, $val_col["id"]);
						$return .= 	'<td align="center">';
						$return .= 		'<select class="'.$params->dropdownmenu.'" onchange="setselectedMatrix(form.q'.$question_id.', this)" name="question['.$question_id.'][menu]['.$val_col["id"].'][answer]['.$value["id"].']" id="q'.$question_id.'a'.$value["id"].$count++.'">';
						$return .= 			'<option value="-1"></option>';						
						
						$edit_val = @$all_values[$val_col["id"]."_".$value["id"]] ? $all_values[$val_col["id"]."_".$value["id"]] : "-1";
						foreach($selected_values as $key_selected=>$value_selected){							
							$selected = "";
							if($edit_val == $value_selected["id"]){								
								if(isset($completed["view_response"]) && $completed["view_response"]=="true"){
									$selected = ' selected="selected" ';									
								}
							}
							$return .= 		'<option '.$selected.' value="'.$value_selected["id"].'">'.$value_selected["value"].'</option>';
						}
						$return .= 		'</select>';
						$return .= 	'</td>';
					}					
				$return .= 	    	'</td>';
				$return .= 	    '</tr>';				    
			}
		}
		$return .= 			'</table>';		
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		$return .= '</table>';
				
		$return .= '<input type="hidden" id="q'.$question_id.'" name="q'.$question_id.'" value="'.$entered.'">';
		$return .= '<input type="hidden" id="qtext'.$question_id.'" name="qtext'.$question_id.'" value="'.$value.'">';
		$return .= '<input type="hidden" name="classes['.$question_id.']" value="QuestionMultiplePerRowMenus">';		
		
		$return_content_array["content"] = $return;
		$return_content_array["validation"] = $validation;
		return $return_content_array;
	}
	
	function getColumns($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_menu_heading');
		$query->where("question_id=".intval($question_id));
		$query->order("id asc");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function getAnswers($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answers');
		$query->where("question_id=".intval($question_id));	
		$query->order("id asc");	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}	
		
	function createValidation($answers, $id, $title){
		$result = "";
		$j = 1;
		$or_array = array();
		
		foreach($answers as $key=>$value){
			$result .= '	i'.$j.' = document.getElementById("q'.$id.'a'.$value["id"].$j.'").value ;'."\n";
			$or_array[] = 'i'.$j.' == -1';
			//$j++;
		}
			
		$result .= '	if('.implode(" || ", $or_array).'){'."\n".
						'		alert(AlertText +"'.addslashes(trim($title)).'");'."\n".
						'		return false;'."\n".
					'	}';			
		return $result;
	}
	
	function getSelectedValues($question_id, $menu_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answer_columns');
		$query->where("question_id=".intval($question_id)." and menu_order=".intval($menu_id));	
		$query->order("id asc");	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function save($id, $type, $session_id){	
		$db =& JFactory::getDBO();
		$all_answers = JRequest::getVar("question");					
		$menus = $all_answers[$id]["menu"];								
		
		if($this->answerExist($id, $session_id)){
			$sql = "delete from  #__ijoomla_surveys_result where q_id=".$id." and session_id=".$session_id;
			$db->setQuery($sql);
			$db->query();
		}
		
		foreach($menus as $key1=>$value1){
			$answers = $value1["answer"];
			foreach($answers as $key2=>$value2){
				if($value2 != -1){
					$sql = "insert into #__ijoomla_surveys_result(`q_id`, `a_id`, `m_id`, `ac_id`, `session_id`, `value`) values (";					
					$sql .= $id.", ".$key2.", ".$key1.", ".$value2.", ".$session_id.", 0";
					$sql .= ")";
					$db->setQuery($sql);
					$db->query();	
				}	
			}												
		}
	}
	
	function answerExist($question_id, $session_id){
		$db =& JFactory::getDBO();
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$question_id." and session_id=".$session_id;
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != "0"){
			return true;
		}
		return false;
	}
	
	function getValue($question_id, $session_id){
        if (!$session_id) { return NULL; }    
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('*');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answer_columns ac');
		$query->where("sr.q_id=".intval($question_id)." and sr.session_id=".intval($session_id)." and sr.ac_id=ac.id");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();				
		return $result;
	}
	
	function getValuesMenus($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('*');
		$query->from('#__ijoomla_surveys_answer_columns ac');
		$query->where("ac.question_id=".$question_id);		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();		
		return $result;
	}
	
	function editResult($id, $survey_id, $params, $i, $title, $all_responses_count){
		$answers = $this->getAnswers($id);
		$columns = $this->getColumns($id);
		$values = $this->getValuesMenus($id);		
		
		$return  = '<table width="100%" style="border:1px solid #CCCCCC; border-collapse:collapse;">';
		$return .= 		'<tr>';
		$return .= 			'<td class="'.$params->question.'" colspan="4" style="padding-left:5px;">';
		$return .= 				'<b>'.$i.". ".$title.'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= 		'<tr>';
		$return .= 			'<td>';
		
		foreach($columns as $c_key=>$c_value){						
			$return .= '<table width="100%">';
			$return .= 		'<tr>';
			$return .= 			'<td bgcolor="#d1e9e9" align="center">';
			$return .= 				$c_value["value"];
			$return .= 			'</td>';
			$return .= 		'</tr>';
			$return .= 		'<tr>';
			$return .= 			'<td>';
			$return .= 				'<table width="100%">';
			$return .= 					'<tr>';
			$return .= 						'<td></td>';
			$columns_for_this_menu = $this->getColumnsForThisMenu($id, $c_value["id"], $values);
			foreach($columns_for_this_menu as $cfm_key=>$cfm_value){
				$return .= '<td align="center">';
				$return .= 		$cfm_value["value"];	
				$return .= '</td>';
			}
			$return .= 						'<td align="center">'.JText::_("COM_SURVEYS_TOTAL_RESPONSE").'</td>';
			$return .= 					'</tr>';						
			$k = 0;
			foreach($answers as $a_key=>$a_value){
				$total_answers = $this->getCountAnswers($id, $a_value["id"], $c_value["id"]);
				$class = $params->table_row1;
				if($k%2 != 0){
					$class = $params->table_row2;
				}
				$k++;
				$return .= '<tr class="'.$class.'">';
				$return .= 		'<td align="right">';
				$return .= 			$a_value["value"];
				$return .= 		'</td>';
				$total_ = 0;
				foreach($columns_for_this_menu as $cfm_key=>$cfm_value){					
					$count = $this->getCountForItemMenu($id, $c_value["id"], $cfm_value["id"], $a_value["id"]);				
					$return .= 		'<td align="center">';
					if($count > 0){
						if(intval($total_answers) != "0"){
							$return .= 	@number_format( (($count * 100) / $total_answers), 2, '.', ''). " %"." (".$count.")";
						}
						$total_ += $count;
					}
					else{
						$return .= '0.00 %';
					}
					$return .= 		'</td>';
				}												
				$return .= 		'<td align="center">';
				$return .= 			$total_;
				$return .= 		'</td>';
				$return .= 	'</tr>';				
			}			
			$return .= 					'<tr>';
			$return .= 						'<td align="right" colspan="'.(count($columns_for_this_menu)+1).'">';
			$return .= 							'<b>'.JTExt::_("COM_SURVEYS_TOTAL_RESPONDENTS").':</b>';
			$return .= 						'</td>';
			$return .= 						'<td class="'.$params->total_background.'" align="center">';
			$return .= 							'<b>'.$total_answers.'</b>';
			$return .= 						'</td>';
			$return .= 					'</tr>';
			$return .= 				'</table>';
			$return .= 			'</td>';
			$return .= 		'</tr>';									
			$return .= '</table>'; // end for each menu
			$return .= "<br />";
		}
		
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= '</table>';
		return $return;
	}	
	
	function getColumnsForThisMenu($id, $menu_order, $values){
		$return = array();
		foreach($values as $key=>$value){
			if($value["menu_order"] == $menu_order){
				$return[] = $value;
			}
		}		
		return $return;
	}
	
	function getCountAnswers($id, $a_id, $m_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and r.session_id=".$r_id;
		}
		$db =& JFactory::getDBO();
		$sql = "SELECT * FROM #__ijoomla_surveys_result as r, #__ijoomla_surveys_session as s WHERE r.q_id=".$id." AND r.a_id=".$a_id." AND r.ac_id > 0 AND r.m_id=".$m_id."  AND r.session_id=s.id AND s.published=1";
		$db->setQuery($sql);
		$db->query();
		$result_array = $db->loadAssocList();
		return count($result_array);	
	}
	
	function getCountForItemMenu($q_id, $m_id, $ac_id, $a_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and r.session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "SELECT * FROM #__ijoomla_surveys_result as r, #__ijoomla_surveys_session as s WHERE r.q_id=".$q_id." AND r.a_id=".$a_id." AND r.ac_id=".$ac_id." AND r.m_id=".$m_id."  AND r.session_id=s.id AND s.published=1".$and;			
		$db->setQuery($sql);
		$db->query();
		$result_array = $db->loadAssocList();
		return count($result_array);
	}
	
	function getValueFromDatabase($question_id, $session_id, $m_id, $a_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('ac.value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answer_columns ac');
		$query->where("sr.q_id=".intval($question_id)." and sr.session_id=".intval($session_id)." and sr.ac_id=ac.id and sr.m_id=".$m_id." and a_id=".$a_id);		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();				
		return $result;
	}	
	
	function getForHeader($id, $title){
		$return_array = array();
		$answers = $this->getAnswers($id);
		foreach($answers as $key=>$value){
			$return_array[] = $title." : ".trim($value["value"]);
		}
		$return = implode(",", $return_array);
		return $return;
	}
	
	function getForRow($q_id, $sess_id){
		$answers = $this->getAnswers($q_id);
		$columns = $this->getColumns($q_id);
		$result_array = array();
		
		foreach($answers as $key=>$value){
			$response = $this->getValueFromDatabase($q_id, $sess_id, $columns["0"]["id"], $value["id"]);			
			if($response != NULL && is_array($response) && count($response) > 0){				
				$result_array[] = $response["0"]["value"];
			}
			else{
				$result_array[] = "NO ANSWER";
			}
		}
		if(count($result_array)>0){
			return implode(",", $result_array);
		}
		else{
			return "NO ANSWER";
		}
	}
	
	function getQuestionResultForEmail($q_id, $session_id, $title){
		$answers = $this->getAnswers($q_id);
		$columns = $this->getColumns($q_id);
		$return = $title.":"."\n";
		
		foreach($answers as $a_key=>$a_value){
			foreach($columns as $c_key=>$c_value){
				$result = $this->getValueFromDatabase($q_id, $session_id, $c_value["id"], $a_value["id"]);
				if(isset($result["0"]["value"]) && trim($result["0"]["value"]) != ""){
					$return .= "\t".trim($a_value["value"])." - ".trim($c_value["value"]).": ".trim($result["0"]["value"]);
				}
				else{
					$return .= "\t".trim($a_value["value"])." - ".trim($c_value["value"]).": ";
				}
				$return .= "\n";								
			}	
		}
		return $return;
	}
	
	function checkCompleted($logic, $compare, $answer, $skip_answer){
		$return = false;
		
		if($logic == "OR"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = true;
						return $return;
					}
				}
			}
			elseif($compare == "different"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
		}
		elseif($logic == "AND"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(!in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
			elseif($compare == "different"){
				foreach($answer as $key=>$value){
					if(in_array($value, $skip_answer)){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
		}			
	}
};

?>
